/**
 *		Licensed to the Apache Software Foundation (ASF) under one
 *     or more contributor license agreements.  See the NOTICE file
 *     distributed with this work for additional information
 *     regarding copyright ownership.  The ASF licenses this file
 *     to you under the Apache License, Version 2.0 (the
 *     "License"); you may not use this file except in compliance
 *     with the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *      Unless required by applicable law or agreed to in writing,
 *     software distributed under the License is distributed on an
 *     "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *     KIND, either express or implied.  See the License for the
 *     specific language governing permissions and limitations
 *     under the License.
 *     
 *     Image Resizer Project
 */

package image.resizer.ui.config;

import image.resizer.ui.NLS;
import image.resizer.ui.ResizerUIConfig;

import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;

/**
 * Image resizer configuration dialog.
 *  
 * @author Dudarev Ilya
 */
public class ConfigurationDialog extends JDialog implements ActionListener {

	private static final String CLASS_NAME = ConfigurationDialog.class.getName();
	private static final Logger logger = Logger.getLogger(ConfigurationDialog.class.getPackage().getName());
	private static final Level FINER_LEVEL = Level.FINER;
	
	private JPanel panel;
	private ResizerUIConfig config;
	
	private static final long serialVersionUID = 1L;

	private static final String CONFIG_TITLE_LABEL = "Image Resizer Configuration";
	
	private static final String CANCELL_BUTTON_LABEL = "Cancell";
	private static final String SAVE_BUTTON_LABEL = "Save";
	private static final String DIRECTORIES_TAB_LABEL = "Directories";
	private static final String PARAMETERS_TAB_LABEL = "Parameters";
	private static final String SYSTEM_TAB_LABEL = "System";
	
	private static final String SEARCH_SUBDIRS_LABEL = "Search subdirectories";
	private static final String MAX_IMAGE_SIZE_LABEL = "Maximal image size";
	private static final String NUM_OF_THREADS_LABEL = "Number of threads";
	
	private static final String INVALID_VALUE_FOR = "Invalid value for {0} : {1}";
	private static final String INVALID_VALUE_TITLE = "Invalid field value";
	private static final String FAILED_TO_SAVE_CONFIG = "Failed to save configuration.";
	private static final String ERROR = "Error";
	
	private JButton saveButton;
	private JButton cancelButton;
	
	
	CheckboxListener searchSubdirsListener;
	NumberTextListener maxImageSizeListener;
	NumberTextListener numOfThreadsListener;
	
	public ConfigurationDialog(Frame frame, ResizerUIConfig config) {
		super(frame, false);
		if(logger.isLoggable(FINER_LEVEL))
		{
			Object[] params = {"frame", frame, "config", config};
			logger.entering(CLASS_NAME, "construcor", params);
		}
		this.config = config;
		setTitle(NLS.formatter.getString(CONFIG_TITLE_LABEL));
		JPanel mainPanel = new JPanel();
		mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
		JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP, JTabbedPane.WRAP_TAB_LAYOUT);
		mainPanel.add(tabbedPane);
		panel = new JPanel();
		tabbedPane.addTab(NLS.formatter.getString(DIRECTORIES_TAB_LABEL), panel);
		getContentPane().add(mainPanel);
		JCheckBox searchSubdirsCheckbox = new JCheckBox(NLS.formatter.getString(SEARCH_SUBDIRS_LABEL), config.isSearchSubDirs());
		searchSubdirsListener = new CheckboxListener(config.isSearchSubDirs());
		searchSubdirsCheckbox.addItemListener(searchSubdirsListener);
		panel.add(searchSubdirsCheckbox);
		
		JPanel formatsPanel = new JPanel();
		GridBagLayout formatsPanelLayout = new GridBagLayout();
		GridBagConstraints formatsPanelConstraints = new GridBagConstraints();
		
		formatsPanel.setLayout(formatsPanelLayout);
		JLabel formatsLabel = new JLabel(NLS.formatter.getString(PARAMETERS_TAB_LABEL));
		formatsPanelConstraints.fill = GridBagConstraints.NONE;
		formatsPanelConstraints.weightx = 0.0;
		formatsPanelConstraints.insets = new Insets(2, 2, 2, 2);
		formatsPanelConstraints.anchor = GridBagConstraints.CENTER;
		formatsPanelConstraints.gridwidth = GridBagConstraints.REMAINDER;
		formatsPanelLayout.setConstraints(formatsLabel, formatsPanelConstraints);
		formatsPanel.add(formatsLabel);
		JLabel maxImageSizeLabel = new JLabel(NLS.formatter.getString(MAX_IMAGE_SIZE_LABEL));
		formatsPanelConstraints.weightx = 0.0;
		formatsPanelConstraints.gridwidth = 1;
		formatsPanelConstraints.fill = GridBagConstraints.NONE;
		formatsPanelLayout.setConstraints(maxImageSizeLabel, formatsPanelConstraints);
		formatsPanel.add(maxImageSizeLabel);
		JTextField maxImageSizeTextField = new JTextField();
		maxImageSizeListener = new NumberTextListener(maxImageSizeTextField);
		maxImageSizeTextField.getDocument().addDocumentListener(maxImageSizeListener);
		maxImageSizeTextField.setText(String.valueOf(config.getMaxImageSize()));
		formatsPanelConstraints.weightx = 1.0;
		formatsPanelConstraints.gridwidth = GridBagConstraints.REMAINDER;
		formatsPanelConstraints.fill = GridBagConstraints.HORIZONTAL;
		formatsPanelLayout.setConstraints(maxImageSizeTextField, formatsPanelConstraints);
		formatsPanel.add(maxImageSizeTextField);
		tabbedPane.addTab(NLS.formatter.getString(PARAMETERS_TAB_LABEL), formatsPanel);
		
		JPanel systemPanel = new JPanel();
		GridBagLayout systemPanelLayout = new GridBagLayout();
		GridBagConstraints systemPanelConstraints = new GridBagConstraints();
		
		systemPanel.setLayout(systemPanelLayout);
		JLabel systemLabel = new JLabel(NLS.formatter.getString(SYSTEM_TAB_LABEL));
		systemPanelConstraints.fill = GridBagConstraints.NONE;
		systemPanelConstraints.weightx = 0.0;
		systemPanelConstraints.insets = new Insets(2, 2, 2, 2);
		systemPanelConstraints.anchor = GridBagConstraints.CENTER;
		systemPanelConstraints.gridwidth = GridBagConstraints.REMAINDER;
		systemPanelLayout.setConstraints(systemLabel, systemPanelConstraints);
		systemPanel.add(systemLabel);
		JLabel numOfThreadsLabel = new JLabel(NLS.formatter.getString(NUM_OF_THREADS_LABEL));
		systemPanelConstraints.weightx = 0.0;
		systemPanelConstraints.gridwidth = 1;
		systemPanelConstraints.fill = GridBagConstraints.NONE;
		systemPanelLayout.setConstraints(numOfThreadsLabel, systemPanelConstraints);
		systemPanel.add(numOfThreadsLabel);
		JTextField numOfThreadsTextField = new JTextField();
		numOfThreadsListener = new NumberTextListener(numOfThreadsTextField);
		numOfThreadsTextField.getDocument().addDocumentListener(numOfThreadsListener);
		numOfThreadsTextField.setText(String.valueOf(config.getNumOfThreads()));
		systemPanelConstraints.weightx = 1.0;
		systemPanelConstraints.gridwidth = GridBagConstraints.REMAINDER;
		systemPanelConstraints.fill = GridBagConstraints.HORIZONTAL;
		systemPanelLayout.setConstraints(numOfThreadsTextField, systemPanelConstraints);
		systemPanel.add(numOfThreadsTextField);
		tabbedPane.addTab(NLS.formatter.getString(SYSTEM_TAB_LABEL), systemPanel);
		
		JPanel downPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		mainPanel.add(downPanel);
		downPanel.add(Box.createHorizontalGlue());
		JPanel buttonsPanel = new JPanel();
		buttonsPanel.setLayout(new GridLayout(1, 2, 2, 2));
		saveButton = new JButton(NLS.formatter.getString(SAVE_BUTTON_LABEL));
		//TODO layout
		saveButton.addActionListener(this);
		buttonsPanel.add(saveButton);
		cancelButton = new JButton(NLS.formatter.getString(CANCELL_BUTTON_LABEL));
		//TODO layout
		cancelButton.addActionListener(this);
		buttonsPanel.add(cancelButton);
		downPanel.add(buttonsPanel);
				
		pack();
		setLocationRelativeTo(frame);
		setVisible(true);
		
		if(logger.isLoggable(FINER_LEVEL))
		{
			logger.exiting(CLASS_NAME, "constructor");
		}
	}
	
	public void actionPerformed(ActionEvent e) {
		if(logger.isLoggable(FINER_LEVEL))
		{
			logger.entering(CLASS_NAME, "actionPerformed", e);
		}
		if(cancelButton == e.getSource())
		{
			if(logger.isLoggable(FINER_LEVEL))
			{
				logger.logp(FINER_LEVEL, CLASS_NAME, "actionPerformed", "Action is \"CANCEL\"");
			}
			config.clearChanges();
			setVisible(false);
		}
		else if(saveButton == e.getSource())
		{
			if(collectChanges())
			{
				config.storeChanges();
				try
				{
					config.saveToFile();
					setVisible(false);
				}
				catch (Exception exp) {
					logger.logp(Level.SEVERE, CLASS_NAME, "actionPerformed", "Failed to save configuration.", exp);
					JOptionPane.showMessageDialog(this, NLS.formatter.getString(FAILED_TO_SAVE_CONFIG), NLS.formatter.getString(ERROR), JOptionPane.ERROR_MESSAGE);
				}
			}
		}
		if(logger.isLoggable(FINER_LEVEL))
		{
			logger.exiting(CLASS_NAME, "actionPerformed");
		}
	}
	
	private boolean collectChanges()
	{
		if(logger.isLoggable(FINER_LEVEL))
		{
			logger.entering(CLASS_NAME, "collectChanges");
		}
		config.setSearchSubDirs(searchSubdirsListener.getSelected()); //TODO ?
		int maxImageSizeInt = maxImageSizeListener.getNumber();
		if(maxImageSizeInt <= 0)
		{
			logger.logp(Level.WARNING, CLASS_NAME, "collectChanges", "Invalid value for "+MAX_IMAGE_SIZE_LABEL+" : "+maxImageSizeListener.getTextValue());
			JOptionPane.showMessageDialog(this, NLS.formatter.getString(INVALID_VALUE_FOR, NLS.formatter.getString(MAX_IMAGE_SIZE_LABEL), maxImageSizeListener.getTextValue()), NLS.formatter.getString(INVALID_VALUE_TITLE), JOptionPane.WARNING_MESSAGE);
			if(logger.isLoggable(FINER_LEVEL))
			{
				logger.exiting(CLASS_NAME, "collectChanges", false);
			}
			return false;
		}
		config.setMaxImageSize(maxImageSizeInt);
		int numOfThreadsInt = numOfThreadsListener.getNumber();
		if(numOfThreadsInt <= 0)
		{
			logger.logp(Level.WARNING, CLASS_NAME, "collectChanges", "Invalid value for "+NUM_OF_THREADS_LABEL+" : "+numOfThreadsListener.getTextValue());
			JOptionPane.showMessageDialog(this, NLS.formatter.getString(INVALID_VALUE_FOR, NLS.formatter.getString(NUM_OF_THREADS_LABEL), numOfThreadsListener.getTextValue()), NLS.formatter.getString(INVALID_VALUE_TITLE), JOptionPane.WARNING_MESSAGE);
			if(logger.isLoggable(FINER_LEVEL))
			{
				logger.exiting(CLASS_NAME, "collectChanges", false);
			}
			return false;
		}
		config.setNumOfThreads(numOfThreadsInt);
		if(logger.isLoggable(FINER_LEVEL))
		{
			logger.exiting(CLASS_NAME, "collectChanges", true);
		}
		return true;
	}
}
